<?php
namespace Api\Controller;
use Think\Controller;
class ShopAdminController extends CommonController {
    public function getInfo(){
    	$map['wid'] = session('wid');
        $map['openid'] = $_GET['openid'];
        $info = M("Shop")->where($map)->find();
        $info['pics'] = explode(",", $info['pics']);

        //今日收入，今日验单数 7日等
        $begin_today = date("Y-m-d 00:00:00",time());
        $begin_week =date("Y-m-d 00:00:00",strtotime("-7 days"));
        $end= date("Y-m-d 23:59:59",time());
        $where['wid'] =  session('wid');
        $where['shop_id'] = $info['shop_id'];
        $where['openid'] = $_GET['openid'];
        //今日收入
        $where['last_time'] = array('between', array($begin_today, $end));
        $info['moneyDay'] = M('ValidateLog')->where($where)->sum('jie_money');
        $info['countDay'] = M('ValidateLog')->where($where)->count();
        //一周内
        $where['last_time'] = array('between', array($begin_week, $end));
        $info['moneyWeek'] = M('ValidateLog')->where($where)->sum('jie_money');
        $info['countWeek'] = M('ValidateLog')->where($where)->count();

        $info['card'] = M('shop_card')->where(['shop_id'=>$info['shop_id']])->find()?1:0;
        $this->ajaxReturn($info);
    }

    public function edit(){
        $map['wid'] = session('wid');
        $map['openid'] = I("openid");
        if ($_POST['card_discount'] > 100 || $_POST['card_discount'] < 0) {
            $arr = array("err_code"=>400,"err_msg"=>"同城卡折扣数据不合法");
            $this->ajaxReturn($arr);
        }
        if(M("Shop")->where($map)->save($_POST)){
            $arr = array("err_code"=>0,"err_msg"=>"修改成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙！");
            $this->ajaxReturn($arr);
        }
    }
    public function editForm(){
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();

        $map['id'] = $_GET['id'];
        $eq['openid'] = I("openid");
        $info = M("Shop")->where($eq)->find();
        $info['pics'] = explode(",", $info['pics']);
        
        $top_input = array('type'=>'top');

        $where['city_code'] = $wechat['city'];
        $city = M("City")->where($where)->find();
        $where1['pid'] = $city['id'];
        $site_arr2 = M("City")->where($where1)->getField("city_name",true);
        if($wechat['city'] == 0){
            $site_arr1 = array("全国");
        }else{
            $site_arr1 = array($city["city_name"]);
            if(!$site_arr2){
                $site_arr2 = array("全辖区");
            }
        }
        $site_input = array(
            'type'=>'picker2', 
            'title'=>'所在区域', 
            'name'=>array('county_name', 'site_name'),
            'range'=>array($site_arr1, $site_arr2),
            'value'=>array(0,0)
        );

        $cate_map['wid'] = session('wid');
        $cate_map['type'] = 'shop';
        $cate_map['pid'] = 0;

        $cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
        // dump($cates);
        foreach ($cates as $k => $v) {
            $cate_map['pid'] = $v['cid'];
            $cate_range[] = $v['title'];
            $sub_cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
            if($sub_cates){
                $cates[$k]['sub_cates'] = $sub_cates;
                foreach ($sub_cates as $key => $value) {
                    $cates[$k]['sub_range'][] = $value['title'];
                }
            }else{
                $cates[$k]['sub_cates'][] = array('cid'=>0, 'title'=>'全部');
                $cates[$k]['sub_range'][] = '全部';
            }
        }
        $cate_input = array(
            'type'=>'picker3',
            'title'=>'店铺分类',
            'cates'=>$cates,
            'name'=>array('cate', 'sub_cate'),
            'range'=>array($cate_range, $cates[0]['sub_range']),
            'value'=>array(0,0),
        );
        $res['add_url'] = "https://www.58zltc.com/api.php/ShopAdmin/edit";
        $res['index_url'] = "/pages/mine/shop/shop";

        $form[] = array('type'=>'text', 'title'=>'店铺名称', 'name'=>'name', 'value'=>$info['name']);
        $form[] = $cate_input;
        $form[] = $site_input;
        $form[] = array('type'=>'text', 'title'=>'店铺地址', 'name'=>'address', 'value'=>$info['address']);
        $form[] = array('type'=>'number', 'title'=>'人均消费', 'name'=>'person_money', 'value'=>$info['person_money']);
        $form[] = array('type'=>'time2', 'title'=>'营业时间', 'name1'=>'start_time', 'value1'=>$info['start_time']?$info['start_time']:'09:00', 'name2'=>'end_time', 'value2'=>$info['end_time']?$info['end_time']:'21:00');
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'店铺Logo', 'name'=>'logo_url', 'num'=>1, 'pics'=>$info['logo_url']?array($info['logo_url']):array());
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'店铺图片', 'name'=>'pics', 'num'=>2, 'pics'=>$info['pics']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'textarea', 'title'=>'详细介绍', 'name'=>'content', 'value'=>$info['content']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'text', 'title'=>'联系人', 'name'=>'username', 'value'=>$info['username']);
        $form[] = array('type'=>'text', 'title'=>'联系电话', 'name'=>'tel', 'value'=>$info['tel']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'text', 'title'=>'同城卡折扣(%)', 'name'=>'card_discount', 'value'=>$info['card_discount']);
        // $form[] = array('type'=>'top');
        // $form[] = array('type'=>'price', 'title'=>'平台入驻费', 'price'=>$wechat['shop_fee'], 'unit'=>'年');
        $res['form'] = $form;
        // $res[''] = 
        $this->ajaxReturn($res);
    }

    public function validate(){
        $chou = 0;//代理抽成
    	$type = I("type");
        $str =explode(',',I("out_trade_no"));//out_trade_no,wid
    	$eq['out_trade_no'] = $str[0];
        $eq['wid'] = $str[1]?$str[1]:session('wid');
    	$eq['is_pay'] = 1;
    	$order = M("order")->where($eq)->find();

    	/*$arr = array("err_code"=>400,"err_msg"=>"未找到相应的订单！");
        $this->ajaxReturn($arr);*/

    	if(!$order){
    		$arr = array("err_code"=>400,"err_msg"=>"未找到相应的订单！",'sql'=>$a);
            $this->ajaxReturn($arr);
    	}
    	$map['wid'] = session("wid");
    	$map['openid'] = I("openid");
    	$shop = M("Shop")->where($map)->find();

    	if(!$shop){
    		$arr = array("err_code"=>400,"err_msg"=>"权限不足！");
            $this->ajaxReturn($arr);
    	}

    	if($shop['shop_id'] != $order['shop_id']){
    		$arr = array("err_code"=>400,"err_msg"=>"未找到相应的订单！");
            $this->ajaxReturn($arr);
    	}
    	if($order['status'] == 2){
    		$arr = array("err_code"=>400,"err_msg"=>"该订单已经验证过了！");
            $this->ajaxReturn($arr);
    	}
    	if($order['status'] == 0 && $order['is_tuan'] == 0){
    		$arr = array("err_code"=>400,"err_msg"=>"该订单尚未拼团成功！");
            $this->ajaxReturn($arr);
    	}

    	if($type == 'getInfo'){
    		$arr = array("err_code"=>0,"data"=>$order);
            $this->ajaxReturn($arr);
    	}elseif($type == 'validate'){
    		$new['status'] = 2;
    		M("Order")->where($eq)->save($new);
    		$data['type'] = 'order';
    		$data['out_trade_no'] = $eq['out_trade_no'];
    		$data['openid'] = $map['openid'];
    		$data['wid'] = $eq['wid'];
    		$data['shop_id'] = $order['shop_id'];
    		$data['all_money'] = $order['pay_money'];
    		$data['yong_money'] = $order['pay_money'] * 10 / 100;
    		$data['yong'] = 10/100;
    		$data['jie_money'] = $data['all_money'] - $data['yong_money'];
    		M("ValidateLog")->add($data);
            $price = $order['pay_money'];

            //判断是否发佣金
            $wid = $order['wid'];
            $wechat = M('wechat')->where(['wid'=>$wid])->find();
            //商品参与分销，并且设置为核销时发佣金
            if(($wechat['good_commission'] == 2)&& $order['is_commission']){
                addGoodCommission($order['wid'],4,$order['id'],$order['openid'],$order['commission_one'],$order['commission_two'],$order['pay_money']);
            }
            //这个时候需要判断到达店铺的金额，有佣金的话从订单里扣
            $commission = M('commission')->where(['orderid'=>$order['id'],'type'=>4])->sum('money');
            $price = $price - $commission;

            $goods = M('goods')->where(['id'=>$order['goods_id']])->find();

            //商品或者店铺抽成
            if($shop['chou']>0 ){
                $chou = ($shop['chou']/100)*$price;
            }
            //商品优先级比较高，优先按照商品的扣除
            if($goods['chou']>0){
                $chou = ($goods['chou']/100)*$price;
            }
            $price = $price- $chou;
    		M("Shop")->where($map)->setInc('money',$price>0?$price:0);
    		$arr = array("err_code"=>0,"err_msg"=>"验单成功！");
            $this->ajaxReturn($arr);
    	}
    }

    public function validateCenter(){
    	$map['wid'] = session("wid");
    	$map['openid'] = I("openid");
    	$shop = M("Shop")->where($map)->find();
    	if(!$shop){
    		$arr = array("err_code"=>400,"err_msg"=>"访问权限不足！");
            $this->ajaxReturn($arr);
    	}

    	$eq['tp_validate_log.shop_id'] = $shop['shop_id'];
    	$list = M("ValidateLog")->field('tp_validate_log.*, b.name, b.logo_url')
            ->join('tp_shop b on tp_validate_log.shop_id = b.shop_id')->where($eq)
            ->order('tp_validate_log.last_time desc')
            ->select();

    	$tabs = array("订单验证记录","优惠券验证记录");

    	$res['shop'] = $shop;
    	$res['list'] = $list;
    	$res['tabs'] = $tabs;
    	$arr = array("err_code"=>0,"data"=>$res);
        $this->ajaxReturn($arr);
    }

    public function validateCoupon () {
        $where['wid'] = session("wid");
        $where['openid'] = I("openid");
        $list = M("coupon_log")->where($where)->select();
        $this->ajaxReturn($list);
    }

    //订单管理  未验证
    public function orderUnValidate(){
        $map['tp_order.wid'] = I("wid");
        $map['tp_order.shop_id'] = I("shop_id");
        $map['tp_order.status'] = '1';
        $map['tp_order.is_pay'] = '1';
        $list = M("order")->field('tp_order.*, b.name, b.logo_url')->join('tp_shop b on tp_order.shop_id = b.shop_id')->where($map)->select();
        $this->ajaxReturn($list);
    }

    //订单管理  已验证
    public function orderIsValidate(){
        $map['tp_order.wid'] = I("wid");
        $map['tp_order.shop_id'] = I("shop_id");
        $map['tp_order.status'] = '2';
        $map['tp_order.is_pay'] = '1';
        $list = M("order")->field('tp_order.*, b.name, b.logo_url')->join('tp_shop b on tp_order.shop_id = b.shop_id')->where($map)->select();
        $this->ajaxReturn($list);
    }

    //
    public function verJoinEndTime () {
        $id = I('shop_id');
        $list = M('shop')->where(['shop_id' => $id])->find();
        if($list){
            $list['join_end_time'] > date('Y-m-d H:i:s', time()) ? $this->ajaxReturn(1) : $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn(0);
        }

    }
}